
package io.github.qifan777.server.rating.controller;
import cn.dev33.satoken.stp.StpUtil;
import io.github.qifan777.server.infrastructure.model.QueryRequest;
import io.github.qifan777.server.rating.entity.Rating;
import io.github.qifan777.server.rating.entity.dto.RatingInput;
import io.github.qifan777.server.rating.entity.dto.RatingSpec;
import io.github.qifan777.server.rating.repository.RatingRepository;
import io.qifan.infrastructure.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.client.meta.DefaultFetcherOwner;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("front/rating")
@AllArgsConstructor
@DefaultFetcherOwner(RatingRepository.class)
@Transactional
public class RatingForFrontController {
    private final RatingRepository ratingRepository;

    @GetMapping("{id}")
    public @FetchBy(value = "COMPLEX_FETCHER_FOR_FRONT") Rating findById(@PathVariable String id) {
        return ratingRepository.findById(id, RatingRepository.COMPLEX_FETCHER_FOR_FRONT).orElseThrow(() -> new BusinessException("数据不存在"));
    }

    @PostMapping("query")
    public Page< @FetchBy(value = "COMPLEX_FETCHER_FOR_FRONT") Rating> query(@RequestBody QueryRequest<RatingSpec> queryRequest) {
        return ratingRepository.findPage(queryRequest, RatingRepository.COMPLEX_FETCHER_FOR_FRONT);
    }
    public String insert(RatingInput input) {
        return ratingRepository.insert(input.toEntity()).id();
    }

    public String update(RatingInput input) {
        Rating rating = ratingRepository.findById(input.getId(), RatingRepository.COMPLEX_FETCHER_FOR_FRONT).orElseThrow(() -> new BusinessException("数据不存在"));
        if (!rating.creator().id().equals(StpUtil.getLoginIdAsString())) {
            throw new BusinessException("只能修改自己的数据");
        }
        return ratingRepository.update(input.toEntity()).id();
    }

    @PostMapping("save")
    public String save(@RequestBody @Validated RatingInput input) {
        return StringUtils.hasText(input.getId()) ? update(input) : insert(input);
    }

    @DeleteMapping
    public Boolean delete(@RequestBody List<String> ids) {
        ratingRepository.findByIds(ids, RatingRepository.COMPLEX_FETCHER_FOR_FRONT).forEach(rating -> {
            if (!rating.creator().id().equals(StpUtil.getLoginIdAsString())) {
                throw new BusinessException("只能删除自己的数据");
            }
        });
        ratingRepository.deleteAllById(ids);
        return true;
    }
}
